﻿#include "linuxsystemmethod.h"
#include <QNetworkInterface>
#include<QDateTime>
QString CPU;//CPU
QString Memory;//内存
QString Disk;//磁盘
QString UpNetword;//网络
QString DoNetword;//网络
QString NetwordName;//
LinuxSystemMethod::LinuxSystemMethod()
{

}
bool LinuxSystemMethod::getCpuInfo() {
    QProcess process;
    process.start("cat /proc/stat");
    process.waitForFinished();

    // Read all lines from the process
    QByteArray result = process.readAllStandardOutput();
    QString str(result);

    // Split the content into lines
    QStringList lines = str.split("\n", QString::SkipEmptyParts);

    // Process the first line (total CPU stats)
    if (lines.size() > 0) {
        QString line = lines[0];
        QStringList values = line.split(QRegExp("\\s+"), QString::SkipEmptyParts);

        if (values.size() > 8) {
            // Extract CPU states
            double user = values[1].toDouble();
            double nice = values[2].toDouble();
            double system = values[3].toDouble();
            double idle = values[4].toDouble();
            double iowait = values[5].toDouble();
            double irq = values[6].toDouble();
            double softirq = values[7].toDouble();

            // Calculate total and used CPU
            double total = user + nice + system + idle + iowait + irq + softirq;
            double used = user + nice + system;

            // Calculate CPU usage percentage
            double cpuUsage = (used / total) * 100.0;

            qDebug() << "CPU Usage:" << QString::number(cpuUsage, 'f', 2) << "%";
            CPU=QString::number(cpuUsage, 'f', 2);
            return true;
        }
    }
    return false;
}

bool LinuxSystemMethod::getNetUsage() {
    QProcess process;
    process.start("cat /proc/net/dev");
    process.waitForFinished();

    // Skip the first two lines (header lines)
    process.readLine();
    process.readLine();
    double m_recv_bytes__ = 0.0;
    double m_send_bytes__ = 0.0;
    //double m_timer_interval__ = 0.0;
    while (!process.atEnd()) {
        QString str = process.readLine();
        str.replace("\n", "");
        str.replace(QRegExp("( ){1,}"), " ");

        auto lst = str.split(" ");
        //  if (lst.size() > 9 && lst[0] == "enp8s0:") {
        if(lst.size() > 9 && lst[0] == "enp8s0:")
        {
            double recv = 0;
            double send = 0;
            if(lst.size() > 1)
                recv = lst[1].toDouble();
            if(lst.size() > 9)
                send = lst[9].toDouble();
            qDebug("recv=%.0lfbyte/s,send%.0lfbyte/s",recv,send);
            qDebug("%s 接收速度:%.0lfmb/s 发送速度:%.0lfmb/s",lst[0].toStdString().c_str(),(recv - m_recv_bytes__) / 1024000.0,(send - m_send_bytes__) / 1024000.0);
            m_recv_bytes__ = recv;
            m_send_bytes__ = send;
        }
        // }
    }

    return true;
}

bool LinuxSystemMethod::getDiskSpeed() {

    double m_disk_read__ = 0.0;
    double m_disk_write__ = 0.0;
    QProcess process;
    process.start("vmstat");
    process.waitForFinished();
    process.readLine(); // Skip the header line
    process.readLine(); // Skip the header line
    QString str = process.readLine();
    qDebug()<<str;
    str.replace("\n", "");
    str.replace(QRegExp("( ){1,}"), " ");
    auto lst = str.split(" ");

    if (lst.size() > 15)

    {
        // Adjust the index based on the actual output of vmstat -d
        qDebug("读取:%.0lfmb/s 写入:%.0lfmb/s", (lst[9].toDouble() - m_disk_read__) , (lst[10].toDouble() - m_disk_write__));
        m_disk_read__ = lst[9].toDouble();
        m_disk_write__ = lst[10].toDouble();
        UpNetword=m_disk_read__;
        DoNetword=m_disk_write__;
        return true;
    }

    return false;
}
QString LinuxSystemMethod::getDiskSpace(QString Path) {
    QThread::msleep(500);
    QProcess process;
    process.start("df -k");
    if (!process.waitForFinished()) {
        qDebug() << "Failed to execute df command.";
        return "";
    }

    process.readLine(); // Skip the header line
    while (!process.atEnd()) {
        QString str = process.readLine();
        qDebug() << "磁盘路径:" << str;
        if (str.startsWith(Path)) {
            str.replace("\n", "");
            str.replace(QRegExp("( ){1,}"), " ");

            auto lst = str.split(QRegExp("\\s+"));


            if (lst.size() > 5) {
                qDebug() << "磁盘路径:" << lst[5].toStdString().c_str()
                         << "总量:" << lst[1].toDouble() / 1024.0 << "MB"
                         << "已用:" << lst[2].toDouble() / 1024.0 << "MB"
                         << "空闲:" << lst[3].toDouble() / 1024.0 << "MB";
                return lst[5].toStdString().c_str();

            }
        }
    }

    return "";
}
bool LinuxSystemMethod::getPathSpace(QString Path) {
    // QThread::msleep(500);
    QProcess process;
    process.start("df");
    if (!process.waitForFinished()) {
        qDebug() << "Failed to execute df command.";
        return false;
    }

    process.readLine(); // Skip the header line
    while (!process.atEnd()) {
        QString str = process.readLine();
        qDebug() << "磁盘路径:" << str;
        if (str.contains(Path)) {
            str.replace("\n", "");
            str.replace(QRegExp("( ){1,}"), " ");

            auto lst = str.split(QRegExp("\\s+"));


            if (lst.size() > 5) {
                qDebug() << "磁盘路径:" << lst[5].toStdString().c_str()
                         << "总量:" << lst[1].toDouble() / 1024.0 << "MB"
                         << "已用:" << lst[2].toDouble() / 1024.0 << "MB"
                         << "空闲:" << lst[3].toDouble() / 1024.0 << "MB";
                return true;
            }
        }
    }

    return false;
}
bool LinuxSystemMethod::getMemUsage()
{
    QProcess process;
    process.start("free -m"); //使用free完成获取
    process.waitForFinished();
    process.readLine();
    QString str = process.readLine();
    str.replace("\n","");
    str.replace(QRegExp("( ){1,}")," ");//将连续空格替换为单个空格 用于分割
    auto lst = str.split(" ");
    if(lst.size() > 6)
    {
        qDebug("总量:%.0lfMB 已用:%.0lfMB 空闲:%.0lfMB",lst[1].toDouble(),lst[2].toDouble(),lst[6].toDouble());

        Memory=lst[2].toDouble()*100/lst[1].toDouble();
        return true;
    }
    return false;
}
bool GetMAC(QString Mac,QString startTime,QString endTime)
{
    QList<QNetworkInterface> interfaces = QNetworkInterface::allInterfaces();
    foreach (const QNetworkInterface &netInterface, interfaces)
    {
        // if (netInterface.flags().testFlag(QNetworkInterface::IsUp) &&
        // netInterface.flags().testFlag(QNetworkInterface::IsRunning))
        // {
        qDebug() << "Interface: " << netInterface.name();
        qDebug() << "MAC Address: " << netInterface.hardwareAddress().remove(':');
        // Get the current timestamp (milliseconds since the epoch)
        qint64 currentTimestamp = QDateTime::currentMSecsSinceEpoch();

        // Convert the timestamp to seconds
        qint64 currentTimestampSeconds = currentTimestamp / 1000;

        // Convert the qint64 timestamp to a QString
        QString timestampString = QString::number(currentTimestampSeconds);
        // Output the current timestamp as a QString
        qDebug() << "Current Timestamp (QString): " << timestampString;


        if(netInterface.hardwareAddress().remove(':')==Mac && startTime<=timestampString && endTime>=timestampString)
        {
            return true;
        }
        // }
    }
    return false;
}
bool isPrivateIP(const QString &ip) {
    // 检查IP地址的前缀
    if (ip.startsWith("10.")) {
        return true; // 10.x.x.x 是私有地址
    } else if (ip.startsWith("172.")) {
        // 172.16.x.x 到 172.31.x.x 是私有地址
        bool isPrivate = false;
        int secondOctet = ip.section('.', 1, 1).toInt(); // 获取第二个八位组（点分隔的第二个部分）
        if (secondOctet >= 16 && secondOctet <= 31) {
            isPrivate = true;
        }
        return isPrivate;
    }
    return false; // 不是私有地址
}

QString getNetworkIP() {
    QProcess process;
    process.start("hostname", QStringList() << "-I");
    if (process.waitForFinished()) {
        QString ipList = process.readAllStandardOutput();
        QStringList ips = ipList.trimmed().split("\\s+"); // 分割IP地址列表

        foreach (const QString &ip, ips) {
            if (!ip.isEmpty() && !isPrivateIP(ip)) {
                qDebug() << "Local IP:" << ip;
                return ip; // 返回第一个找到的非内网IP
            }
        }
    } else {
        qDebug() << "Failed to get IP address";
    }
    return QString(); // 如果没有找到非内网IP，返回空字符串
}
